package com.uhylab.uhuvinetest.activity;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.uhylab.uhuvinetest.MyService;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.UHApplication;
import com.uhylab.uhuvinetest.UHUpdateManager;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseFragment;
import com.uhylab.uhuvinetest.fragment.UHHistoryFragment;
import com.uhylab.uhuvinetest.fragment.UHNewHomeFragment;
import com.uhylab.uhuvinetest.fragment.UHShopFragment;
import com.uhylab.uhuvinetest.fragment.UHUserCenterFragment;
import com.uhylab.uhuvinetest.utils.UHDeviceUtils;
import com.uhylab.uhuvinetest.view.NoScrollViewPager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


public class UHMainActivity extends FragmentActivity implements UHUserCenterFragment.setTextView, UHNewHomeFragment.go2Two {
    private static final String UPDATE_VERSION_ID = "2";
    private List<UHBaseFragment> fragments;
    private long exitTime = 0;// 双击返回间隔时间
    private Intent mStartIntent;
    private boolean is_start_service = false;
    private RadioGroup tg_bottom_tag;
    public NoScrollViewPager viewpager_content;
    public TextView main_title;
    /**
     * 当前Activity的弱引用，防止内存泄露
     **/
    private WeakReference<Activity> context = null;

    private UHApplication uhApplication;
    private UHUserCenterFragment mUhUserCenterFragment;
    private UHNewHomeFragment mUHNewHomeFragment;
    private UHHistoryFragment mUHHistoryFragment;
    private UHShopFragment mUHShopFragment;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mUHNewHomeFragment = new UHNewHomeFragment();
        mUHHistoryFragment = new UHHistoryFragment();
        mUHShopFragment = new UHShopFragment();
        mUhUserCenterFragment = new UHUserCenterFragment();

        initView();
        initData();

        initViewListener();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (resultCode) {
            case 1:
                mUhUserCenterFragment.pregnancyChange(data.getStringExtra("date"));
                break;
            case 2:
                finish();
                startActivity(new Intent(this, UHMainActivity.class));
                break;
        }

    }

    private void initView() {


        uhApplication = new UHApplication();
        context = new WeakReference<Activity>(this);
        uhApplication.pushTask(context);

        tg_bottom_tag = (RadioGroup) findViewById(R.id.tg_bottom_tag);
        tg_bottom_tag.check(R.id.rb_home);
        viewpager_content = (NoScrollViewPager) findViewById(R.id.viewpager_content);
        mStartIntent = new Intent(this, MyService.class);
        startService(mStartIntent);
        is_start_service = true;
    }


    private void initViewListener() {

        viewpager_content.setOffscreenPageLimit(3);

        viewpager_content.setAdapter(new ContentFragmentAdapter(getSupportFragmentManager()));

        //监听RadioGroup的状态
        tg_bottom_tag.setOnCheckedChangeListener(new MyOnCheckedChangeListener());

        //设置监听页面的改变
        viewpager_content.addOnPageChangeListener(new MyOnPageChangeListener());

        viewpager_content.setCurrentItem(0, false);
        OkHttpUtils.get()
                .url(UHBase.getNewVersion)
                .addParams("device", UPDATE_VERSION_ID)
                .addParams("appversion", String.valueOf(UHDeviceUtils.getVersionCode(this)))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        Log.e("UHMainActivity", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.get("code").equals("0000")) {
                                JSONObject data = (JSONObject) jsonObject.get("data");
                                String newversion = (String) data.get("newversion");
//                                final int version = Integer.parseInt(newversion);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        /**
                                         * 检测更新版本
                                         */
                                        new UHUpdateManager(UHMainActivity.this).checkUpdate("", 4, "");
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

    @Override
    public void toTwo(String date) {
        //viewpager_content.setCurrentItem(1, false);
        mUHHistoryFragment.toLastTest(date);
    }


    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_home:
                    viewpager_content.setCurrentItem(0, false);
                    break;
                case R.id.rb_history:
                    viewpager_content.setCurrentItem(1, false);
                    break;
                case R.id.rb_shop:
                    viewpager_content.setCurrentItem(2, false);
                    break;
                case R.id.rb_user:
                    viewpager_content.setCurrentItem(3, false);
                    break;
            }
        }
    }

    private void initData() {


        fragments = new ArrayList<>();

        fragments.add(mUHNewHomeFragment);
        fragments.add(mUHHistoryFragment);
        fragments.add(mUHShopFragment);
        fragments.add(mUhUserCenterFragment);

    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (is_start_service) {
            stopService(mStartIntent);
            is_start_service = false;
        }

    }


    /**
     * 双击返回的Toast提示
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(UHMainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }

        }
        return false;
    }


    public void set(String s) {
    }


    class ContentFragmentAdapter extends FragmentPagerAdapter {
        public ContentFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

//        @Override
//        public int getCount() {
//            return fragments.size();
//        }
//
//        @Override
//        public boolean isViewFromObject(View view, Object object) {
//            return view == object;
//        }
//
//        @Override
//        public Object instantiateItem(ViewGroup container, int position) {
//            UHBasePager basePager = fragments.get(position);
//            View rootView = basePager.rootView;
//            container.addView(rootView);
//
//            //basePager.initData();
//
//            return rootView;
//        }
//
//
//
//        @Override
//        public void destroyItem(ViewGroup container, int position, Object object) {
//            container.removeView((View) object);
//        }
//    }
    }


}
